var cache = {};
var server = require("http").createServer(function(req, res) {
	if (req.method === "GET") {
		var headers = req.headers;
		var resCache = cache[req.headers["user-id"]];
		if (resCache == undefined || req.headers["user-id"] == undefined || req.headers["user-pass"] == undefined) {
			res.writeHead(404, {"Content-Type": "application/json"});
			res.write('{"success": false}');
			res.end();
		} else {
			if (headers["user-pass"] === resCache.pass) {
				res.writeHead(200, {"Content-Type": "application/json"});
				res.write(JSON.stringify({success: true, value: resCache.value}));
				res.end();
			} else {
				res.writeHead(401, {"Content-Type": "application/json"});
				res.write('{"success": false}');
				res.end();
			}
		}
	} else if (req.method === "POST") {
		var data = "";
		req.on("data", function(chunk) {
			data += chunk;
		});

		req.on("end", function() {
			data = JSON.parse(data);
			if (cache[data.id] === undefined) {  //New
				cache[data.id] = {pass: data.pass, value: data.value};
				res.writeHead(200);
				res.end();
			} else {                                    //Update
				if (cache[data.id].pass === data.pass) {
					cache[data.id].value = data.value;
					res.writeHead(200);
					res.end();
				} else {
					res.writeHead(401);
					res.end();
				}
			}
		});
	}
});

server.listen(13274);
